package net.alan.modules.task;

import net.alan.modules.bean.Project;
import net.alan.modules.bean.User;
import net.alan.modules.bean.WorkStat;
import net.alan.modules.handle.BaseExecption;
import net.alan.modules.service.IProjectService;
import net.alan.modules.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com
 * 2017年12月19日 下午2:24:39
 */
@Component
public class UserCountTask {
    @Autowired
    IUserService userService;
    @Autowired
    IProjectService projectService;

    /**
     * 查询分钟粒度的用户数量入缓存
     */
    @Scheduled(cron = "5 0/1 * * * ?")
    public void miniute() {
        long projects = projectService.count(Project.class);
        long users = userService.count(User.class);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);

        long logins = userService.getLoginsByCreated(cal.getTime());
        long registers = userService.getRegistersByLastLogin(cal.getTime());

        saveWorkStat("projects", projects);
        saveWorkStat("users", users);
        saveWorkStat("registers", registers);
        saveWorkStat("logins", logins);
    }

    private void saveWorkStat(String name, long value) {
        WorkStat ws = userService.getWorStat(name);
        ws.setValue(value);
        try {
            userService.save(WorkStat.class, ws);
        } catch (BaseExecption baseExecption) {
            baseExecption.printStackTrace();
        }
    }


}
